//
//  CycLanguage.m
//  Cycling
//
//  Created by cjg.mini on 2023/4/11.
//

#import "CycLanguage.h"

static CycLanguage *_sharedInstance;

NSString * const CycAppLanguageKey = @"appLanguage";

NSString * const CycChinesePrefix = @"zh-Hans";
NSString * const CycEnglishPrefix = @"en";

NSString * const CycChineseLanguageName = @"简体中文";
NSString * const CycEnglishLanguageName = @"English";


@implementation CycLanguage

+ (CycLanguage *)sharedInstance {
    @synchronized (self) {
        if (!_sharedInstance) {
            _sharedInstance = [[CycLanguage alloc] init];
        }
        return _sharedInstance;
    }
}

- (void)configLanguage {
    NSString *currentLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:CycAppLanguageKey];
    if (!currentLanguage) {
        currentLanguage = CycEnglishPrefix;
    }
    [self setLanguage:currentLanguage];
}

- (NSString *)currentLanguage {
    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:CycAppLanguageKey];
    if (language) {
        if ([language isEqualToString:CycChinesePrefix]){ // 中国语言只有简体中文
            return @"zh";
        }
        return language;
    }
    return CycEnglishPrefix;
}

- (void)setLanguage:(NSString *)language {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:language forKey:CycAppLanguageKey];
    [defaults synchronize];
}

- (void)setLanguageWithLanguageName:(NSString *)languageName {
    if ([languageName isEqualToString:CycChineseLanguageName]) {
        [self setLanguage:CycChinesePrefix];
    } else if ([languageName isEqualToString:CycEnglishLanguageName]) {
        [self setLanguage:CycEnglishPrefix];
    } else {
        [self setLanguage:CycEnglishPrefix];
    }
}

- (BOOL)isChinese {
    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:CycAppLanguageKey];
    if (language) {
        if ([language isEqualToString:CycChinesePrefix]){ // 中国语言只有简体中文
            return YES;
        }
        return NO;
    }
    return NO;
}

@end
